package com.qingshu.TEST;

import java.lang.reflect.Field;

/**
 * 描述
 *
 * @author Huzz
 * @create 2022-05-10 14:42
 */
public class ThreadTool {

    public static Thread createThread(Runnable custRunnable, String name){
        return new Thread(custRunnable, name);
    }

    public static Thread createThread(Class<? extends Thread> custThread, String name) {
        Thread thread = null;
        try {
            thread = custThread.newInstance();
            setThreadName(name, thread);
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }

        return thread;
    }

    public static Thread createRunnableThread(Class<?> custRunnable, String name) {
        Runnable runnable = null;
        try {
            // 初始化自定义线程任务
            runnable = (Runnable) custRunnable.newInstance();
            // 设置线程名称
            setThreadName(name, runnable);
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }

        return new Thread(runnable, name);
    }

    /**
     * 设置线程名称
     * @param name
     * @param o
     * @throws IllegalAccessException
     */
    private static void setThreadName(String name, Object o) throws IllegalAccessException {
        Field[] fields = o.getClass().getDeclaredFields();
        for (Field field : fields) {
            field.setAccessible(true);
            if ("name".equals(field.getName()) || "threadName".equals(field.getName())) {
                field.set(o, name);
            }
        }
    }

}
